// const { get } = require("request")

Page({
    data: {
        formName: '',
        formPhone: '',
        formpassword: ''
    },

    //注册
    zhuce() {
        //获取输入的信息
        let name = this.data.formName
        let phone = this.data.formPhone
        let password = this.data.formpassword
        console.log("点击了注册")
        console.log("name", name)
        console.log("zhanghao", phone)
        console.log("mima", password)
        //校验用户名
        if (name.length < 2) {
            wx.showToast({
                icon: 'none',
                title: '用户名至少2位',
            })
            return
        }
        if (name.length > 10) {
            wx.showToast({
                icon: 'none',
                title: '用户名最多10位',
            })
            return
        }
        //校验账号
        if (phone.length < 11) {
            wx.showToast({
                icon: 'none',
                title: '手机账号至少11位',
            })
            return
        }
        //校验密码
        if (password.length < 4) {
            wx.showToast({
                icon: 'none',
                title: '密码至少4位',
            })
            return
        }
        //去重
        wx.cloud.database().collection('my_user').where({
            phone: phone
        }).get({
            success(res) {
                console.log("获取数据成功", res)
                let user = res.data[0]
                console.log("user", user)
                if (user && phone == user.phone) {
                    console.log('检测到相同账号');
                    wx.showToast({
                        icon: 'none',
                        title: '账号已存在',
                    })
                    return
                }
               if(!user){
                    console.log('未检测到相同账号');
                    //注册功能的实现
                    wx.cloud.database().collection('my_user').add({
                        data: {
                            name: name,
                            phone: phone,
                            password: password
                        },
                        success(res) {
                            console.log('注册成功', res)
                            wx.showToast({
                                title: '注册成功',
                            })
                            wx.redirectTo({
                                url: '/mypages/sign/sign',
                            })
                        },
                        fail(res) {
                            console.log('注册失败', res)
                        }
                    })
                }
            },
            fail(res) {
                console.log("获取数据失败", res)

            }
        })

    },
})

